/*
 * @Author: xiaosihan 
 * @Date: 2023-08-10 11:24:00 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2023-11-25 10:55:54
 */

import designEditor from "@/editorComponent/designEditor";
import editorStore from "@/editorComponent/editorStore";
import { Input, Slider } from "antd";
import clsx from "clsx";
import { clamp, throttle } from "lodash";
import { autorun } from "mobx";
import { useEffect, useRef, useState } from "react";
import styles from "./toolRotation.module.less";
import nameNumStore from "@/editorComponent/LeftMenu/NameNum/nameNumStore";


interface Iprops {
}

// 旋转
export default function ToolRotation() {

  const dom = useRef<HTMLDivElement | null>(null);
  const [visible, setVisible] = useState(false);
  const [disable, setDisable] = useState(false);
  const [rotation, setRotation] = useState(editorStore.rotation);

  useEffect(() => autorun(() => {
    const { lock, activeObjectId } = editorStore;
    const { step } = nameNumStore;
    const activeObject = designEditor.fabricCanvas.getActiveObject();
    if (activeObjectId && activeObject) {
      const lockNameNum = (["name", "num"].includes(activeObject.name || "") && step === 3);
      setDisable(lock || lockNameNum);
      setVisible(true);
    } else {
      setVisible(false);
    }
  }), []);

  useEffect(() => autorun(() => {
    setRotation(editorStore.rotation);
  }), []);

  const activeObjectRotation = throttle((angle: number) => {
    const activeObject = designEditor.fabricCanvas.getActiveObject();
    if (activeObject) {
      activeObject.angle = angle;
      designEditor.render();
    }
  }, 30);

  return (
    <div
      className={clsx(styles.toolRotation, visible && styles.visible, disable && styles.disable)}
    >
      <span className={styles.lable} >旋转</span>
      <Slider
        className={styles.slider}
        min={-180}
        max={180}
        value={rotation}
        onChange={v => {
          activeObjectRotation(v);
          editorStore.setRotation(v);
        }}
      />
      <Input
        key={rotation}
        className={styles.input}
        defaultValue={rotation}
        onPressEnter={e => {
          designEditor.setRotation(Number((e.target as HTMLInputElement).value));
        }}
        onBlur={e => {
          designEditor.setRotation(Number((e.target as HTMLInputElement).value));
        }}
        onWheel={e => {
          const value = clamp((rotation - Math.sign(e.deltaY)), -180, 180);
          designEditor.setRotation(value, 0);
        }}
      />
    </div>
  );

}